package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HaoHanYouJieDES;
import com.block.datapush.service.apipush.utils.HaoHanYouJieUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 97 浩瀚有借 回调
 */
@Service
public class HaoHanYouJiePushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    MerchantBaseInfoMapper merchantBaseInfoMapper;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        if (StrUtil.isEmpty(memberSourceInfo.getIdcard())){
            pushApiResult.setCode("500");
            pushApiResult.setMessage("身份证为空");
            return pushApiResult;
        }

        String queryUrl = StrUtil.format(pushApiKeyParam.getCheckUrl(), pushApiKeyParam.getApiCode());
        String phoneMd5 = memberSourceInfo.getMobileMd5();
        String nameMd5 = SecureUtil.md5(memberSourceInfo.getRealname()).toLowerCase();
        String idnoMd5 = SecureUtil.md5(memberSourceInfo.getIdcard()).toLowerCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("name_md5", nameMd5);
        bizMap.put("idno_md5", idnoMd5);
        bizMap.put("phone_md5", phoneMd5);
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("sex",memberSourceInfo.getSex()==1?"男":"女" );
        bizMap.put("ip",memberSourceInfo.getReqIp());
        bizMap.put("working_city",memberSourceInfo.getProvince()+"/"+memberSourceInfo.getCity());
        bizMap.put("salary_type","银行代发");
        bizMap.put("loan_amount", HaoHanYouJieUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loan_period",HaoHanYouJieUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("reserved_funds", HaoHanYouJieUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("social_security", HaoHanYouJieUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("credit_record",HaoHanYouJieUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("insurance",HaoHanYouJieUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("real_estate",HaoHanYouJieUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("zhima",HaoHanYouJieUtil.getzhima(memberSourceInfo.getZhima()));
        bizMap.put("car",HaoHanYouJieUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("industry",HaoHanYouJieUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("loan_lately", "没有申请过贷款");

        String content = HaoHanYouJieDES.encrypt(JSON.toJSONString(bizMap), pushApiKeyParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("data", content);

        log.info("【浩瀚有借】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【浩瀚有借】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            String tid = resultObject.getString("tid");

            extJson.put("tid",tid);

            pushApiResult.setOutOrderNo(tid);
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = StrUtil.format(pushApiKeyParam.getRegisterUrl(), pushApiKeyParam.getApiCode());

        String checkTid = extJson.getString("tid");

        String phoneMd5 = SecureUtil.md5(memberSourceInfo.getMobile()).toLowerCase();
        String nameMd5 = SecureUtil.md5(memberSourceInfo.getRealname()).toLowerCase();
        String idnoMd5 = SecureUtil.md5(memberSourceInfo.getIdcard()).toLowerCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("check_tid", checkTid);

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String redirect_url = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());
        bizMap.put("redirect_url", redirect_url);
        bizMap.put("name_md5", nameMd5);
        bizMap.put("idno_md5", idnoMd5);
        bizMap.put("phone_md5", phoneMd5);
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex() == 1 ? "男" : "女");
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("working_city", memberSourceInfo.getProvince() + "/" + memberSourceInfo.getCity());
        bizMap.put("salary_type", "银行代发");
        bizMap.put("loan_amount", HaoHanYouJieUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loan_period", HaoHanYouJieUtil.getloanTime(memberSourceInfo.getLoanTime()));
        bizMap.put("reserved_funds", HaoHanYouJieUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("social_security", HaoHanYouJieUtil.getshebao(memberSourceInfo.getShebao()));
        bizMap.put("credit_record", HaoHanYouJieUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("insurance", HaoHanYouJieUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("real_estate", HaoHanYouJieUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("zhima", HaoHanYouJieUtil.getzhima(memberSourceInfo.getZhima()));
        bizMap.put("car", HaoHanYouJieUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("industry", HaoHanYouJieUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("loan_lately", "没有申请过贷款");
        bizMap.put("phone_pre", memberSourceInfo.getMobile().substring(0,3));



        log.info("【浩瀚有借】导单开始【queryUrl】{}【bizMap】{}", requestUrl, JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【浩瀚有借】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {

            String url = resultObject.getString("url");
            String tid = resultObject.getString("tid");

            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(tid);
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_QUERY.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        pushApiResult.setOrderNo(pushQueryParam.getOrderNo());

        String requestUrl = StrUtil.format(pushApiKeyParam.getQueryUrl(), pushApiKeyParam.getApiCode());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("tid", pushQueryParam.getOutOrderNo());

        log.info("【浩瀚有借】查询开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【浩瀚有借】查询结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());

        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();


        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) throws Exception {

        String infoId = extObject.getString("infoId");

        JSONObject paramObject = JSON.parseObject(paramContent);
        String tid = paramObject.getString("tid");

        MerchantDataPushInfo merchantDataPushInfo = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, tid);

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(infoId);

        MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectById(merchantDataPushInfo.getUid());

        JSONObject dataObject = new JSONObject();
        dataObject.put("tid", tid);
        dataObject.put("name", memberSourceInfo.getRealname());
        dataObject.put("idno",  memberSourceInfo.getIdcard());
        dataObject.put("phone",  memberSourceInfo.getMobile());

        String data = HaoHanYouJieDES.encrypt(JSON.toJSONString(dataObject), merchantBaseInfo.getApiSecret());

        JSONObject returnData = new JSONObject();
        returnData.put("data", data);

        JSONObject result = new JSONObject();
        result.put("returnData", returnData);
        result.put("resultData", dataObject);

        return result;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

}
